import {
  Config
} from 'config';
const config = new Config();
var app = getApp();

// 基础类
/**
 * 基础方法库
 */
class Base {
  /**
   * //只要文件名，不要扩展名
   */
  getFilename(name){
    if (!name) return '';
    let index = name.lastIndexOf('.');
    if(index==-1){
      return name;
    }
    //只要文件名，不要扩展名
    return name.substring(0, index);

  }
  
  /**
   * 计算字符串长度
   */
  getStringLength(str) {
    if (str == null) return 0;
    if (typeof str != "string") {
      str += "";
    }
    return str.replace(/[^\x00-\xff]/g, "01").length;
  }

  /**
   * @description base64编码方法
   * @param val 需要编码的字符串
   * @return 返回编码好的base64字符串
   */
  encodingBase64(val) {
    let base64hash = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

    //把字符串转换为字符数组
    let strArr = val.split('')

    //装入结果的数组
    let result = []
    //每个字符的ascii码
    let asciiCode
    //上一个字符的ascii码
    let prevAsciiCode

    let mod
    //未填充之前的数组与3的模
    let preMod = strArr.length % 3

    //使字符数组组成三个一组
    if (preMod == 1) {
      strArr.push(null)
      strArr.push(null)
    }
    if (preMod == 2) strArr.push(null)
    //遍历整个数组，寻找每个字符的ascii码
    for (let index in strArr) {
      if (!strArr[index]) {
        asciiCode = 0
      } else {
        asciiCode = strArr[index].charCodeAt()
      }
      //位于一组当中的第几个字符
      mod = index % 3
      switch (mod) {
        case 0:
          //往右移2位
          result.push(base64hash[asciiCode >> 2])
          break
        case 1:
          //上一个ascii码往左移4位与现在的ascii码往右移四位做或操作
          result.push(base64hash[(prevAsciiCode & 3) << 4 | asciiCode >> 4])
          break
        case 2:
          result.push(base64hash[(prevAsciiCode & 15) << 2 | asciiCode >> 6])
          result.push(base64hash[asciiCode & 63])
          break
      }

      prevAsciiCode = asciiCode
    }

    //处理异常
    if (preMod == 1) {
      result.splice(result.length - 2, 2)
      result.push('==')
    } else if (preMod == 2) {
      result.pop()
      result.push('=')
    }

    return result.join('')
  }


  base64_decode (input) { // 解码，配合decodeURIComponent使用
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
        enc1 = base64EncodeChars.indexOf(input.charAt(i++));
        enc2 = base64EncodeChars.indexOf(input.charAt(i++));
        enc3 = base64EncodeChars.indexOf(input.charAt(i++));
        enc4 = base64EncodeChars.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    return utf8_decode(output);
}

  /**
   * 根据类型返回中文名
   */
  value2Name(type, code) {
    let name = code;
    let dictionary = wx.getStorageSync('dictionary');
    for (let i = 0; i < dictionary[type].length; i++) {
      let item = dictionary[type][i];
      if (item.dataValue == code) {
        name = item.dataName;
        break;
      }
    }
    return name;
  }

  /**
 * 根据类型返回字典
 */
  getDictionary(type) {
    let dictionary = wx.getStorageSync('dictionary');
    return dictionary[type];
  }

  /**
   * 获得输入框中的值
   * @param {string} event 事件对象
   */
  getInputContent(event) {
    return event.detail;
  }

  /**
   * 获得元素上的绑定的值
   * @param {object} event 事件对象
   * @param {string} key 键值
   */
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  }

  /**
   * 获取事件对象值
   * @param {object} event 事件对象
   * @param {string} key 键值
   */
  getEventDetail(event, key) {
    return event.detail[key];
  }

  /**
   * 跳转到指定的路径
   * @param {string} path 跳转路径
   * @param {string} type 跳转类型
   */
  pathTo(path, type = 'nav') {
    if (type == 'nav') {
      wx.navigateTo({
        url: path
      });
    } else if (type == 'tab') {
      wx.switchTab({
        url: path
      });
    } else if (type == 'redirect') {
      wx.redirectTo({
        url: path
      });
    } else if (type == 'relaunch') {
      wx.reLaunch({
        url: path
      });
    } else if (type == 'navBack') {
      wx.navigateBack({
        delta: 1
      });
    }
  }
  /**
   * 返回到指定的页面
   * @param {string} page 返回页面
   */
  navigateBackToPage(page){
    let pages = getCurrentPages();//当前页面

    for (let i = pages.length - 1; i >= 0; i--) {
      let prevPage = pages[i];
      if (prevPage.route == page) {
        wx.navigateBack({
          delta: pages.length - 1 - i
        })
        break;
      }
    }
  }
  /**
   * 获取token令牌
   */
  //getToken() {
  //  return wx.getStorageSync('token').access_token;
  //}


  /**
   * 显示toast
   * @param {string} title toast标题
   * @param {string} type toast类型
   * @param {number} duration toast时长
   * @param {boolean} mask 是否显示遮罩
   */
  showToast(title, type = 'none', duration = 2000, mask = false) {
    wx.showToast({
      title: title,
      icon: type,
      duration: duration,
      mask: mask
    });
  }

  /**
   * 显示操作弹框
   * @param {Array} itemList 项目列表
   * @param {string} color 项目颜色
   */
  showActionSheet(itemList, color = '#666666') {
    return new Promise((resolve, reject) => {
      wx.showActionSheet({
        itemList: itemList,
        itemColor: color,
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
        },
        complete: () => {}
      });
    });
  }

  /**
   * 显示加载中
   * @param {string} title 标题
   */
  showLoading(title = '加载中...', mask=true) {
    wx.showLoading({
      title: title,
      mask: true
    });
  }

  /**
   * 隐藏loading
   */
  hideLoading() {
    wx.hideLoading();
  }

  /**
   * 显示模态框
   * @param {string} title 模态框标题
   * @param {string} content 模态框内容
   * @param {boolean} showCancel 是否显示取消按钮
   * @param {string} cancelText 取消文字 
   * @param {string} cancelColor 取消文字颜色
   * @param {string} confirmText 确认文字
   * @param {string} confirmColor 确认文字颜色
   */
  showModal(title, content, showCancel = true, cancelText = '取消',
    cancelColor = '#888888', confirmText = '确认', confirmColor = '#ed712d') {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: title,
        content: content,
        showCancel: showCancel,
        cancelText: cancelText,
        cancelColor: cancelColor,
        confirmText: confirmText,
        confirmColor: confirmColor,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('failed')
        }
      });
    });
  }

  /**
   * 修改导航栏背景颜色
   * @param {string} backColor 背景颜色
   */
  setNaviBarColor(frontColor, backColor) {
    wx.setNavigationBarColor({
      frontColor: frontColor,
      backgroundColor: backColor,
      animation: {
        duration: 300,
        timingFunc: 'linear'
      }
    });
  }

  /**
   * 选择相册图库或者拍照
   * @param {string} target 选择打开方式 
   * @param {number} count 选择图库的数量
   */
  chooseImage(target, count) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: count,
        sizeType: ['original', 'compressed'],
        sourceType: [target], // 'album','camera'
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('取消选图');
        },
        complete: () => {}
      });
    });
  }

  /**
   * 打开微信地址页面
   */
  openWechatAddress() {
    return new Promise((resolve, reject) => {
      wx.chooseAddress({
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('地址初始化');
        },
        complete: () => {

        }
      });
    });
  }

  /**
   * 设置缓存
   * @param {string} key 键值
   * @param {object} data 存储数据对象
   */
  setStorage(key, data) {
    return new Promise((resolve, reject) => {
      wx.setStorage({
        key: key,
        data: data,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('fail');
        },
        complete: () => {}
      });
    });
  }


  /**
   * 从本地缓存中异步获取指定 key 的内容
   * @param {string} key 本地缓存中指定的 key
   */
  getStorage(key) {
    return new Promise((resolve, reject) => {
      wx.getStorage({
        key: key,
        success: (res) => {
          resolve(res);
        },
        fail: (res) => {
          reject(res);
        },
        complete: () => {}
      });
    });
  }


  /**
   * 获得图片信息
   * @param {string} src 图片url
   */
  getImageInfo(src) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: src,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('fail')
        },
        complete: () => {}
      });
    });
  }

  /**
   * 保存画布为临时图片
   * @param {string} canvasId 画布id
   * @param {string} fileType 文件格式
   * @param {number} quality 图片质量
   */
  saveCanvas(canvasId, fileType = 'jpg', quality = 1.0) {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        canvasId: canvasId,
        fileType: fileType,
        quality: quality,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('save canvas failed');
        },
        complete: () => {}
      }, this);
    });
  }

  /**
   * 保存图片至手机相册
   * @param {string} filePath 图片路径
   */
  saveImage(filePath) {
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('save image failed');
        },
        complete: () => {

        }
      });
    });
  }


  /**
   * 拨打电话 
   * @param {string} telNumber 电话号码
   */
  makePhoneCall(telNumber) {
    wx.makePhoneCall({
      phoneNumber: telNumber
    });
  }

  /**
   * 设置剪切板内容
   * @param {string} data 复制内容
   */
  setClipboardData(data) {
    var _this = this;
    wx.setClipboardData({
      data: data,
      success: (res) => {
        _this.showToast('复制成功', 'success');
      },
      fail: () => {},
      complete: () => {}
    });
  }

  /**
   * 封装网络请求，使用Promise简化回调
   * @param {object} param 
   */
  request(param, url, method = "GET") {
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: param,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: method,
        dataType: 'json',
        responseType: 'text',
        success: (res) => {
          if(res.statusCode==401){
            //token失效了
            wx.removeStorageSync('token');
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }
          resolve(res)
        },
        fail: () => {
          reject('请求超时')
        },
        complete: () => {}
      });
    });
  }


  /**
   * 上传文件
   */
  uploadFile(url, filePath, name, formData) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: url,
        filePath: filePath,
        name: name,
        formData: formData,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('请求超时');
        },
        complete: () => {}
      });
    });
  }


  /**
   * 微信登陆
   */
  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        timeout: 10000,
        success: (res) => {
          resolve(res);
        },
        fail: () => {
          reject('登录超时');
        },
        complete: () => {}
      });
    });
  }




};



export {
  Base
};